package com.lxs.mall.controller;

import com.alibaba.fastjson.JSONObject;
import com.lxs.common.constant.AuthConstant;
import com.lxs.common.constant.SMSConstant;
import com.lxs.common.exception.BizCodeEnum;
import com.lxs.common.utils.R;
import com.lxs.common.vo.MemberVO;
import com.lxs.mall.feign.MemberFeignService;
import com.lxs.mall.feign.SmsFeignService;
import com.lxs.mall.vo.LoginVO;
import com.lxs.mall.vo.UserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {
    @Autowired
    SmsFeignService smsFeignService;
    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/sms/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, Model model) {
        Map map = new HashMap<String, String>();
        if (result.hasErrors()) {
            //表示提交的数据不合法
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field, defaultMessage);
            }
            model.addAttribute("error", map);
            return "/reg";
        } else {
            //检查验证码是否正确
            String code = (String) redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
            code = code.split("_")[0];
            if (!code.equals(vo.getCode())) {
                //验证码不正确
                map.put("code", "验证码错误");
                model.addAttribute("error", map);
                return "/reg";
            } else {
                //验证码正确
                //删除缓存中的验证码
                redisTemplate.delete(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
                //远程调用对应的服务完成注册功能
                R r = memberFeignService.register(vo);
                if (r.getCode() == 0) {
                    //注册成功，返回登陆页面
                    return "redirect:http://auth.lxsde.com/login.html";
                } else {
                    map.put("msg", r.getCode() + ":" + r.get("msg"));
                    model.addAttribute("error",map);
                    return "/reg";
                }
            }
        }
    }
    @PostMapping("/login")
    public String login( LoginVO vo, HttpSession httpSession){
        R r = memberFeignService.login(vo);
        if(r.getCode()==0){
            String entityJson= (String) r.get("entity");
            MemberVO memberVO= JSONObject.parseObject(entityJson,MemberVO.class);
            httpSession.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
            // 表示登录成功
            return  "redirect:http://mall.lxsde.com/home";
        }else{
            httpSession.setAttribute("errors", r.get("msg"));

            // 表示登录失败,重新跳转到登录页面
            return "redirect:http://auth.lxsde.com/login.html";
        }
    }

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //防止60秒内重复发送验证码
        Object redisCode = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + phone);
        if (redisCode != null && StringUtils.isNotEmpty(redisCode.toString())) {
            long l = Long.parseLong(redisCode.toString().split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(BizCodeEnum.VALID_SMS_EXCEPTION.getCode(), BizCodeEnum.VALID_SMS_EXCEPTION.getMsg());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5);
        R r = smsFeignService.sendCode(phone, code);
        code = code + "_" + System.currentTimeMillis();
        System.out.println("code = " + code);
        redisTemplate.opsForValue().set(SMSConstant.SMS_CODE_PERFIX + phone, code, 5, TimeUnit.MINUTES);
        return r;
    }
}
